var ajax = require('../../utils/ajax.js');
var common = require('../../utils/common.js');
var Pagination = require('../../utils/pagination.js');
var app = getApp();
var curPage;
var curScope;
var _onSearch;
var _pagination;

function init({
  page,
  scope,
  cmpt
}) {
  curPage = page;
  curScope = scope || 'nearShopList';

  _initLayout();
  _getLoaction();

  curPage['nearShopList.markertap'] = _markertap;
}

function onReachBottom() {
  var _self = curPage;
  if (!_pagination) { //未初始化
    return;
  }
  var pageParams = _getData('pageParams');

  if (!pageParams || pageParams.pageLoadedAll) {
    return;
  }

  _pagination && _pagination.loadNext();
}

function _initLayout() {
  wx.getSystemInfo({
    success: function(res) {
      var winHeight = res.windowHeight;

      _setData({
        mapHei: winHeight * 0.5,
        listHei: winHeight * 0.8,
      })
    }
  });
}

function _markertap(evt) {
  var id = evt.markerId;
  var markers = _getData('markers');

  markers.forEach(function(item) {
    item.active = id == item.id;
  });

  _setData({
    markers
  });

  // curPage.toMap({
  //   address: curItem.address,
  //   name: curItem.title
  // });
}

/**
 * 获取gps定位
 */
function _getLoaction() {
  var nearShopData = _getData();
  var {
    lat,
    lng
  } = app.getLocation();

  nearShopData.locating = true;
  nearShopData.lat = lat;
  nearShopData.lng = lng;
  _setData(nearShopData);

  // if (!lat || !lng) {
  wx.getLocation({
    success: function(result) {
      var lat = result.latitude;
      var lng = result.longitude;

      app.setLocation(lat, lng);

      nearShopData.gpsFail = false;
      nearShopData.lat = lat;
      nearShopData.lng = lng;
      _setData(nearShopData);

      _getNearShop();
    },
    fail: function(result) {
      nearShopData.gpsFail = true;
      _setData(nearShopData)
    }
  });
  // } else {
  //   _getNearShop();
  // }
}

/**
 * 重新授权共享地址
 */
function _getGPS(evt) {
  var formId = evt.detail.formId;

  wx.openSetting({
    success: function(res) {
      _getLoaction();
    }
  })
  common.submitForm(formId);
}

/**
 * 获取最近的店
 */
function _getNearShop() {
  var {
    lat,
    lng
  } = app.getLocation();
  var pageParams = {
    nextPageLoading: false,
    pageLoadedAll: false,
  };

  _setData({
    markers: [],
    includePoints: [{
      latitude: lat,
      longitude: lng
    }],
    pageParams
  });

  var nearShopData = _getData();

  if (_pagination) {
    _pagination.flush();
    return;
  }

  _pagination = new Pagination({
    url: '/openapi/CHome/nearbyStoresList',
    params: {
      lng,
      lat,
    },
    beforeGetPage(page) {
      var pageParams = _getData('pageParams');

      if (page > 1) {
        pageParams.nextPageLoading = true;
        _setData(pageParams);
      }
    },
    getPageSuccess(page, data) {
      var nearShopData = _getData();
      var {
        markers = [], pageParams = {}, includePoints = [{
          latitude: lat,
          longitude: lng
        }]
      } = nearShopData;
      var nearList = data.result['nearbyStoresList'] || [];
      var newMarkers = [],
        newPoints = [];


      newMarkers = nearList.map(function(item, index) {
        newPoints.push({
          latitude: item.lat,
          longitude: item.lng
        });

        if (item.juli <= 100) {
          item.juli = '100米以内';
        } else if (item.juli <= 1000) {
          item.juli = item.juli + ' m';
        } else {
          item.juli = (parseFloat(item.juli) / 1000).toFixed(2) + ' km';
        }

        return {
          id: item.id,
          latitude: item.lat,
          longitude: item.lng,
          title: item.title,
          iconPath: "/images/redaddr.png",
          width: 30,
          height: 30,
          juli: item.juli,
          address: item.address,
          contact: item.contact
        };
      });

      nearShopData.markers = markers.concat(newMarkers);
      nearShopData.includePoints = includePoints.concat(newPoints);
      nearShopData.locating = false;

      if (page == 1) {
        nearShopData.dataLoaded = true;
      }
      if (newMarkers.length < 10) {
        pageParams.pageLoadedAll = true;
      }
      pageParams.nextPageLoading = false;

      nearShopData.pageParams = pageParams;

      _setData(nearShopData);
    }
  });
}

function _setData(data) {
  var obj = _getData();

  Object.assign(obj, data);

  curPage.setData({
    [`${curScope}`]: obj
  });
}

function _getData(key) {
  var data = curPage.data[`${curScope}`] || {};

  if (!key) {
    return data;
  } else {
    return data[key];
  }
}

module.exports = {
  init: init,
  onReachBottom,
};